package com.assets.Scrap;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Adapter.Addrepairs_Adapter1;
import com.assets.Adapter.Addrepairs_Adapter_new;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.bean.AddRepairs_bean1;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.SoftKeyBoardListener;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/5/9.
 */

public class Scrap_Add extends BaseActivity1 {

    private static final String TAG = "添加报废单页面";

    private ImageView fh;
    private String url = "http://" + Url.IP + "/api/scrapAddInspect";
    private String upload_url = "http://" + Url.IP + "/api/scrapAdd";
    private List<String> numbers = new ArrayList<>();//编号集合
    private List<String> remarks = new ArrayList<>();//集合s
    private List<AddRepairs_bean1> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private ListView listView;
    private EditText et, et_num, et_reason;
    private Button scan_img, uploading, btn_rfid;
    private LinearLayout ll_bottom;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scrap_add);
        inview();
    }

    private void inview() {
        et_num = (EditText) findViewById(R.id.et_num);
        et_num.setFocusableInTouchMode(true);
        et_num.requestFocus();
        et = (EditText) findViewById(R.id.remark);
        et_reason = (EditText) findViewById(R.id.reason);
        uploading = (Button) findViewById(R.id.upload);
        listView = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
                    if (S.equals(data.get(i).getCode_number())) {
                        Toast.makeText(Scrap_Add.this, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(et_num.getText().toString().trim())) {
                        scanAssetNumber(et_num.getText().toString().trim());
                    } else {
                        Toast.makeText(Scrap_Add.this, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                    }

                } else {
//                    Toast.makeText(Scrap_Add.this, "错误的格式", Toast.LENGTH_SHORT).show();
                }
            }
        });

        scan_img.setOnClickListener(v -> startQrCode());
        listView.setOnItemLongClickListener((parent, view, i, id) -> {
            new AlertView(" 提示！", "是否删除", "取消", new String[]{"确定"}, null, Scrap_Add.this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        for (int j = 0; j < lv_data.size(); j++) {
                            if (lv_data.get(j).equals(data.get(i).getCode_number())) {
                                lv_data.remove(j);
                            }
                        }
                        data.remove(i);
                        Addrepairs_Adapter_new adapter_item = new Addrepairs_Adapter_new(Scrap_Add.this, R.layout.addrepairs_item, data, "报废");
                        listView.setAdapter(adapter_item);
                    }
                }
            }).setCancelable(true).show();
            return true;
        });

        uploading.setOnClickListener(v -> {
            if (data.size() > 0) {
                new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Scrap_Add.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            numbers.clear();
                            remarks.clear();
                            for (int i = 0; i < data.size(); i++) {
                                numbers.add(data.get(i).getCode_number());
                                remarks.add(data.get(i).getRemark());
                            }
                            updata();
                        }
                    }
                }).setCancelable(true).show();
            } else {
                Toast.makeText(Scrap_Add.this, "请扫码添加需报废的资产", Toast.LENGTH_SHORT).show();
            }
        });
        ll_bottom = findViewById(R.id.suspension);
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(this);
        softKeyBoardListener.setOnSoftKeyBoardChangeListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                ll_bottom.setVisibility(View.INVISIBLE);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 1);
                params.height = 1;
                params.topMargin = 0;
                params.bottomMargin = 0;
                ll_bottom.setLayoutParams(params);
            }

            @Override
            public void keyBoardHide(int height) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                ll_bottom.setLayoutParams(params);
                ll_bottom.setVisibility(View.VISIBLE);
            }
        });
        TextView title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("添加报废单");
        btn_rfid = findViewById(R.id.btn_rfid);
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
        initRFID();
    }

    private void updata() {
        showDialog("提交数据");
        Map<String, String> map = new HashMap<>();
        map.put("assetNumbers", numbers.toString());
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("operator", Since_case.getInstance().getUserId());
        map.put("remark", et.getText().toString());
        map.put("reason", et_reason.getText().toString());
        map.put("reasons", remarks.toString());

        newPostScrap("华哥新增的报废接口", map, responseData ->  {

            // TODO: 2023/12/7 这个地方就是返回的数据
            Log.d(TAG, "responseData: " + responseData);
            try {
                JSONObject json = new JSONObject(responseData);
                if (json.getString("state").equals("1")) {
                    /*data.clear();
                    lv_data.clear();
                    Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Scrap_Add.this, R.layout.addrepairs_item, data);
                    runOnUiThread(() -> { listView.setAdapter(adapter_item); });*/
                    Intent intent = new Intent(Scrap_Add.this, Scrap_dispose.class);
                    intent.putExtra("scrapId", json.getString("scrapId"));
                    startActivity(intent);
                    finish();
                }
                if (json.getString("state").equals("0")) {
                    showToast("提交失败");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                canDialog();
            }

        }, () -> {
            canDialog();
        });
//        post(upload_url, map, responseData -> {
//            try {
//                JSONObject json = new JSONObject(responseData);
//                if (json.getString("state").equals("1")) {
//                    /*data.clear();
//                    lv_data.clear();
//                    Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Scrap_Add.this, R.layout.addrepairs_item, data);
//                    runOnUiThread(() -> { listView.setAdapter(adapter_item); });*/
//                    Intent intent = new Intent(Scrap_Add.this, Scrap_dispose.class);
//                    intent.putExtra("scrapId", json.getString("scrapId"));
//                    startActivity(intent);
//                    finish();
//                }
//                if (json.getString("state").equals("0")) {
//                    showToast("提交失败");
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            } finally {
//                canDialog();
//            }
//        }, () -> {
//            canDialog();
//        });
    }

    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                readAssetEpc(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }

    /**
     *  扫码查询
     * @param scanResult 二维码
     */
    private void scanAssetNumber(final String scanResult) {
        Map<String, String> map = new HashMap<>();
        map.put("assetNumber", scanResult);
        map.put("userId", Since_case.getInstance().getUserId());
        newPostScrapScan("华哥新增的报废扫码", map, responseData -> {
            handleAssetData(responseData);
            Log.d(TAG, "responseData: " + responseData);
        });
//        post(url, map, responseData -> {
//            handleAssetData(responseData);
//        });
    }

    /**
     * RFID读取查询
     * @param epc
     */
    private void readAssetEpc(final String epc) {
        Map<String, String> map = new HashMap<>();
        map.put("rfid", epc);
        map.put("userId", Since_case.getInstance().getUserId());
        EPCPostNew("这个是华哥新增的本地读卡接口", map, responseData -> {
            Log.d(TAG, "EPC: " + responseData);
            handleAssetData(responseData);
        }, () -> {

        });
//        post(url, map, responseData -> {
//            handleAssetData(responseData);
//        }, () -> {
//            this.map.remove(epc);
//        });
    }

    /**
     * 资产查询数据处理
     * @param responseData 回调数据
     */
    private void handleAssetData(String responseData) {
        LogUtils.d(responseData);
        try {
            JSONObject json = new JSONObject(responseData);
            if (json.getString("state").equals("0")) {
                showToast("失败");
            }
            if (json.getString("state").equals("1")) {
                JSONObject jsonObject = json.getJSONObject("asset");
                String assetName = jsonObject.getString("assetName");
                String deptId = jsonObject.getString("deptId");
                String assetNumber = jsonObject.getString("assetNumber");
                if (lv_data.contains(assetNumber)) {
                    showToast("该资产已存在列表");
                    return;
                }
                lv_data.add(assetNumber);
//                String deptId = jsonObject.getString("userId");
                String userId = jsonObject.getString("userId");
                String model = jsonObject.getString("model");
                String type = jsonObject.getString("type");//type
                String rfid1 = jsonObject.getString("rfid");
                String remark = jsonObject.getString("remark");
                String image = jsonObject.getString("image");
                String jifang = jsonObject.getString("financialCode");
                String jigui = jsonObject.getString("accountant");
                if (!TextUtils.isEmpty(image)) {
                    image = "http://" + Url.IP + image;
                }
                data.add(0, new AddRepairs_bean1(json.getString("state"), image, assetName, "待提交显示", assetNumber, userId, model, type, remark, "类别", rfid1, jifang, jigui));
                Addrepairs_Adapter_new adapter_item = new Addrepairs_Adapter_new(Scrap_Add.this, R.layout.addrepairs_item, data, "报废");
                runOnUiThread(() -> listView.setAdapter(adapter_item));
            }
            if (json.getString("state").equals("2")) {
                showToast("不存在此资产");
            }
            if (json.getString("state").equals("3")) {
                showToast("此资产已报废");
            }
            if (json.getString("state").equals("4")) {
                showToast("当前资产未在用");
            }
            if (json.getString("state").equals("5")) {
                showToast("该资产已申请报废");
            }
            if (json.getString("state").equals("6")) {
                showToast("资产非当前报废人持有，无权报废");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Scrap_Add.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Scrap_Add.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Scrap_Add.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Scrap_Add.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Scrap_Add.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            final String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            for (int i = 0; i < data.size(); i++) {
                if (scanResult.equals(data.get(i).getCode_number())) {
                    Toast.makeText(Scrap_Add.this, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (!lv_data.contains(scanResult)) {
                scanAssetNumber(scanResult);
            } else Toast.makeText(Scrap_Add.this, "该资产已存在列表", Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Scrap_Add.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Scrap_Add.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

}
